package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;

import cloudContact.Common;
import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.GoogleContact;
import cloudContact.DAO.GoogleContactDAO;
import cloudContact.DAO.User;
import cloudContact.DAO.UserDAO;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.util.ServiceException;
import com.google.gson.Gson;

/**
 * Servlet implementation class GoogleContactList
 */
@WebServlet("/GoogleContactList")
public class GoogleContactList extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoogleContactList() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Start GoogleContactList...");

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		try {
			if (!SecurityManager.CheckAuthorization(request)) {
				out.println("Error: User is not authorized.");
				return;
			}

			HttpSession session = request.getSession();

			User user = null;
			try {
				user = UserDAO.getInstance().lookup(
						session.getAttribute("userId").toString());
			} catch (RollbackException e) {
				e.printStackTrace();
			} catch (MyDAOException e) {
				e.printStackTrace();
			}

			if (user == null) {
				out.println("Error: User not found.");
				return;
			}

			GoogleOAuthParameters oauthParameters = GoogleConstant
					.getGoogleOAuthParameters(user.getGMailAccessToken(),
							user.getGMailAuthSecrete(), user.getUserId());
			GoogleContactDAO gContactDAO = GoogleContactDAO
					.getInstanceForSession(session.getId(), oauthParameters);

			Hashtable<ContactGroupEntry, ArrayList<GoogleContact>> groupList = null;
			try {
				groupList = gContactDAO
						.getAllContactsWithGroup();
			} catch (java.lang.NullPointerException e) {
				System.out.println("NullPointerException is throw. Try again with - " + user.getGMailAccessToken() + " : " + user.getGMailAuthSecrete());
				groupList = gContactDAO
						.getAllContactsWithGroup();
			}

			// Group name is specified.
			if (request.getParameter("groupname") != null
					&& !request.getParameter("groupname").toString().equals("")) {
				String groupname = request.getParameter("groupname").toString();

				ArrayList<GoogleContact> contactList = null;

				for (Map.Entry<ContactGroupEntry, ArrayList<GoogleContact>> groupEntry : groupList
						.entrySet()) {
					if (groupname.equals(groupEntry.getKey().getTitle()
							.getPlainText())) {
						contactList = groupEntry.getValue();
					}
				}

				if (contactList == null) {
					out.println("Error: group name not found :" + groupname);
					return;
				}

				Hashtable<String, String> fullNameList = new Hashtable<String, String>();

				for (GoogleContact contact : contactList) {
					fullNameList.put(contact.getContactId(),
							contact.getFullName());
					System.out.println(contact.getContactId());
				}

				Gson gSon = new Gson();
				out.print(gSon.toJson(fullNameList));
			}

		} catch (OAuthException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (ServiceException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
			System.out.println("Finish GoogleContactList.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
